const EPS = 1E-5;

const indiReg = {};

function registerIndicator (name, desc) {

  const ind = document.createElement('div');
  const des = document.createElement('div');
  ind.innerText = '0';
  des.innerText = desc;
  document.getElementById('indis').append(des, ind);

  indiReg[name] = {
    value: 0, 
    set(newVal){
      const val = parseFloat(newVal.toFixed(5));
      this.value = val;
      ind.innerText = val;
    }
  };
}

const frag = new Frag(bezierRect({height: 0.9, width: 0.9}));

function addStrokeSpec({segs}, affected) {
  frag.addStrokeSpec(segs.map(e=>e), affected);
}

function runStrokeSpec() {

  frag.runStrokeSpec();
  
  const strokeTorques = frag.sect.map(sect => Torque.sum(sect.diff((head, tail) => Torque.fromVecs(head, tail))));
  const {center:massCenter} = Torque.sum(strokeTorques);
  massCenter.mult_(0.5);
  console.log(massCenter, 'MASS CENTER')
  const dev = frag.succ.map(({poly}) => Math.abs(area(poly))).stdDev();
  const mag = massCenter.mag();

  for (let sectSpec of frag.sectSpec) {
    sectSpec.offset ??= new Vec();
    sectSpec.offset.plus_(massCenter.neg())
  }

  indiReg['dev'].set(dev);
  indiReg['mag'].set(mag);

  frag.runStrokeSpec(massCenter.neg());

  return { dev, mag };

}

registerIndicator('dev', '被笔画划分面积标准差');
registerIndicator('mag', '重心至原点Euclid距离');

addStrokeSpec({name: '横', segs:[{head: ':L', tail:':R', curvatureType: 'HORIZ'}]});
addStrokeSpec({name: '撇', segs:[{head: '0:DR=>F', tail: '1:DL', curvatureType: 'LEFAL'}]}, [1]);
// addStrokeSpec({name: '撇点', segs: [{head: '2:C', tail: '1:C', curvatureType: 'LEFAL'}]});
addStrokeSpec({name: '撇点', segs: [{head: '2:C', tail: '1:C', curvatureType: 'LEFAL'}, {head: '1:C', tail: '0:DR', curvatureType:'DOTTO'}]});


function parse(string) {
  const lines = string.split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0);

  for (let line of lines) {
    const [name, rest] = line.split(':-');
    const [points, affected] = rest.split('@');
    const pointSegs = points.trim().split(/\s/);
    // console.log('S', pointSegs);
    if (pointSegs.length === 0) {
      const [centSeg] = pointSegs;
      const [cent, angle='0'] = centSeg.split('-');
      addStrokeSpec(name, [{cent, angle:parseFloat(angle)}]);
    } else {
      
    }
  }

}

document.getElementById('code').onkeyup = function handleInput(e) {
  e.preventDefault();
  e.stopPropagation();

  if (e.key === 'Enter' && e.ctrlKey) {
    parse(e.target.value);
  }
}

function draw() {
      
  ctx.clearRect(-400, -400, 800, 800);
  frag.draw(ctx, {lineWidth: 2, drawBezier: true});
  
  const strokeTorques = frag.sect.map(sect => Torque.sum(sect.diff((head, tail) => Torque.fromVecs(head, tail))));
  const {center:massCenter} = Torque.sum(strokeTorques);
  massCenter.mult_(0.5);

  ctx.point(massCenter, {fillStyle: '#F00'});
  ctx.point(new Vec(0, 0), {fillStyle: '#F00'});
}

document.getElementById('code').focus();

runStrokeSpec();
draw()
